using System;
using System.Diagnostics;
using log4net;

namespace BlueCrest.ConfigManagement.Core.Logging
{
    public class LoggerFactory : ILoggerFactory
    {
        private static readonly object LockObject = new object();
        private static bool _configured;

        public LoggerFactory()
        {
            
        }

        public ILogger Create(Type type)
        {
            // Dev note: - double lock check
            if (!_configured)
            {
                lock (LockObject)
                {
                    if (!_configured)
                    {
                        // Get config from app config
                        log4net.Config.XmlConfigurator.Configure();
                        _configured = true;
                    }
                }
            }

            return new Logger(LogManager.GetLogger(type));
        }

        public ILogger Create<T>()
        {
            return Create(typeof(T));
        }

        /// <summary>
        /// Gets the logger for the given type (uses StackFrame to get the calling type)
        /// </summary>
        /// <returns></returns>
        public ILogger Create()
        {
            var callingType = new StackFrame(1, false).GetMethod().DeclaringType;

            return Create(callingType);
        }
    }
}
